package com.zx.designpattern.base;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

import com.zx.designpattern.utils.interfaceforall.FunctionManager;
import com.zx.designpattern.presenter.BasePresenter;
import com.zx.designpattern.view.IBaseView;

import butterknife.ButterKnife;

/**
 * @作者 周翔
 * @创建时间 2018/2/3
 * @描述 Activity基类
 * @修改时间 2018/2/3
 * @修改描述 Activity基类
 * @修改者 周翔
 **/
public abstract class BaseActivity<V, T extends BasePresenter<V>> extends AppCompatActivity implements IBaseView {
    //表示层引用
    public T basePresenter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getRootViewId());
        ButterKnife.bind(this);//绑定ButterKnife
        basePresenter = createPresenter();//新建presenter
        if (basePresenter != null)
            basePresenter.attachView((V) this);//attachview
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (basePresenter != null)
            basePresenter.detachView();//detachView 防止内存泄漏

        removeInterface();
    }


    protected abstract T createPresenter();

    @Override
    public void showLoading() {
        startLoading();

    }

    @Override
    public void hideLoading() {
        stopLoading();
    }

    public ProgressDialog pd;

    public void startLoading() {
        if (pd == null) {
            pd = new ProgressDialog(this);
        }
        if (this.isFinishing() || pd.isShowing()) return;
        pd.show();
    }

    public void stopLoading() {
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
            pd = null;
        }
    }

    @Override
    public void onStop() {
        super.onStop();

        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
    }

    protected abstract int getRootViewId();//activity的layoutid


    //给当前fragment增加接口
    public void setFunctionForFragment(String fragmentTag) {
        FragmentManager mFragmentManager = getSupportFragmentManager();
        BaseFragment baseFragment = (BaseFragment) mFragmentManager.findFragmentByTag(fragmentTag);
        if (baseFragment != null) baseFragment.setmFunctionManager(addInterfaceForFragment());
    }

    //给fragment增加接口
    protected FunctionManager addInterfaceForFragment() {
        return null;
    }

    //移除接口
    protected void removeInterface() {
    }


}
